#include "../curl/CurlClient.h"
#include "../http/HttpData.h"
#include "../common/global.h"
#include "../common/CCReactor.h"
#include <iostream>
#include <thread>
#include <chrono>
#include <vector>

void test_client_thread(int thread_id) {
    std::cout << "Thread " << thread_id << " starting..." << std::endl;
    
    try {
        CurlClient client;
        if (!client.Initialize()) {
            std::cout << "Thread " << thread_id << " failed to initialize client" << std::endl;
            return;
        }
        
        std::cout << "Thread " << thread_id << " client initialized" << std::endl;
        
        // Simple request
        stHttpRequest req;
        req.method = "GET";
        req.url = "http://httpbin.org/get";
        req.heads["User-Agent"] = "ThreadTest/1.0";
        req.heads["X-Thread-Id"] = std::to_string(thread_id);
        
        stHttpResponse resp;
        int result = client.Request(std::move(req), resp);
        
        std::cout << "Thread " << thread_id << " request completed: " << result << std::endl;
        
    } catch (const std::exception& e) {
        std::cout << "Thread " << thread_id << " exception: " << e.what() << std::endl;
    }
    
    std::cout << "Thread " << thread_id << " finished" << std::endl;
}

int main() {
    std::cout << "=== Thread Test ===" << std::endl;
    
    try {
        // Initialize reactor
        g_reactor->Init();
        g_reactor->Start();
        
        std::cout << "Reactor initialized" << std::endl;
        
        // Test with multiple threads
        const int num_threads = 5;
        std::vector<std::thread> threads;
        
        std::cout << "Creating " << num_threads << " threads..." << std::endl;
        
        for (int i = 0; i < num_threads; i++) {
            threads.emplace_back(test_client_thread, i);
            std::this_thread::sleep_for(std::chrono::milliseconds(100));
        }
        
        std::cout << "Waiting for threads to complete..." << std::endl;
        
        for (auto& thread : threads) {
            thread.join();
        }
        
        std::cout << "All threads completed" << std::endl;
        
        g_reactor->Stop();
        
    } catch (const std::exception& e) {
        std::cout << "Test failed with exception: " << e.what() << std::endl;
        return 1;
    }
    
    return 0;
}